package com.devops.admin.special;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.devops.admin.model.DOSMetrics;
import com.devops.admin.model.DOSResource;
import com.devops.admin.service.DOSMetricsService;
import com.devops.admin.service.DOSResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author jxt
 * @Notes
 * @date 2024/9/30 14:43
 */
@Component
public class DynamicDataSourceApplicationRunner implements ApplicationRunner {
    @Autowired
    private DOSMetricsService dosMetricsService;
    @Autowired
    private DOSResourceService dosResourceService;
    @Autowired
    DynamicRoutingDataSource dynamicRoutingDataSource;
    @Override
    public void run(ApplicationArguments args) {
        List<DOSMetrics> dosMetrics = dosMetricsService.getBaseMapper().selectList(Wrappers.lambdaQuery());
        dosMetrics.stream().map(DOSMetrics::getDbName).distinct().forEach(this::initDataSource);
    }

    private void initDataSource(String dbName) {
        DOSResource resource =
                dosResourceService.getOne(Wrappers.<DOSResource>lambdaQuery().eq(DOSResource::getType, 1).eq(DOSResource::getName, dbName));
        if (resource != null && resource.getId() != null && resource.getId() > 0) {
            DruidDataSource druidDataSource = new DruidDataSource();
            druidDataSource.setUrl(resource.getUrl());
            druidDataSource.setUsername(resource.getUsers());
            druidDataSource.setPassword(resource.getPassword());
            druidDataSource.setDriverClassName(resource.getDriverName());
            if (!dynamicRoutingDataSource.getDataSources().containsKey(dbName)) {
                dynamicRoutingDataSource.addDataSource(dbName, druidDataSource);
            }
        }
    }

}
